package com.lagou.rabbitmq.demo.controller;

import com.lagou.rabbitmq.demo.dao.OrderDao;
import com.lagou.rabbitmq.demo.pojo.Order;
import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.UnsupportedEncodingException;
import java.util.Calendar;
import java.util.List;

@Controller
public class SettlementController {
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private AmqpTemplate amqpTemplate;


    @RequestMapping("/Shopping")
    public String toLoginPage(Model model){

        model.addAttribute("currentYear", Calendar.getInstance().get(Calendar.YEAR));
        return "Shopping";
    }


    @RequestMapping("/settlement/{second}")
    public String settlement(Model model,@PathVariable Integer second,String goods) throws UnsupportedEncodingException {
        final MessageProperties messageProperties = MessagePropertiesBuilder.newInstance()
                // 设置消息的过期时间
                .setHeader("x-delay", second  * 1000)
                .setContentEncoding("utf-8")
                .build();
        double random = Math.random();
        int order_no=(int)(random*100000000);
        String msg=order_no+"";

        final Message message = MessageBuilder
                .withBody(msg.getBytes("utf-8"))
                .andProperties(messageProperties)
                .build();

        amqpTemplate.send("ex.delayed", "key.delayed", message);
        Order order=new Order();
        order.setOrder_no(order_no+"");
        order.setO_type("0");
        orderDao.save(order);


        model.addAttribute("order_no", order_no);

        return "settlement";
    }


    @RequestMapping("/pay")
    public String pay(String order_no) throws UnsupportedEncodingException {
       /* List<Order> orders = orderDao.queryByOrder_no(order_no);
        System.out.println(order_no);
        orderDao.updateStatusById(order_no);
        return "settlement";*/

        List<Order> orders = orderDao.queryByOrder_no(order_no);
        if(orders!=null && orders.size()>0){
            if("0".equals(orders.get(0).getO_type())){
                orderDao.updateStatusById(order_no);
                return "success";
            }else{
                return "err";
            }
        }else {
            return "err";
        }


    }




}
